package com.wzy.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author wzy
 * @Date 2023/12/27 15:07
 * @description: 全局异常处理器
 */
@Slf4j
@ControllerAdvice//控制器增强 基于aop切面实现异常捕获
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(CustomException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse restErrorResponse(CustomException customException){
        log.error("【系统异常】{}",customException.getMessage(),customException);
        return new RestErrorResponse(customException.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse restErrorResponse(Exception exception){
        log.error("系统异常:{}",exception.getMessage(),exception);
        if(exception.getMessage().equals("不允许访问")){
            return new RestErrorResponse("你没有权限！");
        }
        return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse methodArgumentNotValidException(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        //用来存储错误信息
        List<String> errorInfos = new ArrayList<>();
        bindingResult.getAllErrors().stream().forEach(item->{
            errorInfos.add(item.getDefaultMessage());
        });
        //将list中的错误信息拼接起来才能返回给前端
        String error = StringUtils.join(errorInfos, ",");
        log.error("系统异常:{}",exception.getMessage(),error);
        return new RestErrorResponse(error);
    }
}
